package com.zy.edu.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.zy.edu.bean.*;
import com.zy.edu.config.SystemParam;
import com.zy.edu.dao.CourseDao;
import com.zy.edu.service.*;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.zy.edu.util.FileUpload;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author HuangHaiShui
 * @since 2021-07-17
 */
@Service
@Transactional
public class CourseServiceImpl extends ServiceImpl<CourseDao, Course> implements CourseService {

    @Resource
    UserService userService;

    @Resource
    CourseChapterService courseChapterService;

    @Resource
    CourseChapterClassService courseChapterClassService;

    @Resource
    CourseChapterSignService courseChapterSignService;
    @Resource
    CourseChapterDocService courseChapterDocService;
    @Resource
    CourseChapterVideoService courseChapterVideoService;

    @Override
    public Map saveOrUpdate(Course course,InputParam inputParam) {

        //当前用户的信息
        User currentUser = userService.selectById(inputParam.getUserId());
        //只有超管和校管可以上传课程
        if(currentUser.getRoleType().equals(Role.SUPER)
                ||currentUser.getRoleType().equals(Role.SCHOOL)) {
            if (StringUtils.isEmpty(course.getId())) {
                course.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                course.setCreateTime(new Date());
                course.setStatus(1);
                //校管上传的课程，要关联学校
                if(currentUser.getRoleType().equals(Role.SCHOOL)) {
                    course.setSchoolId(currentUser.getSchoolId());
                    course.setJurisId(currentUser.getJurisId());
                    course.setType(6);//学校独有课程分类 固定 校本课程
                }
                this.baseMapper.insert(course);
            } else {
                this.baseMapper.updateById(course);
            }
            return ResponseInfo.success(null);
        }else {
            return ResponseInfo.error("您无权限创建课程");
        }
    }

    @Override
    public Map list(Course course, InputParam inputParam) {

        User currentUser = userService.selectById(inputParam.getUserId());

        if(currentUser.getRoleType().equals(Role.TEACHER) &&!inputParam.isOwn()){
            //若是教师且非校本课程 特殊处理，需要查询自己所在班级的课程
           return getByTeacherId(course,inputParam);
        }

        EntityWrapper<Course> entityWrapper = new EntityWrapper<Course>();
        if(!StringUtils.isEmpty(course.getName())){
            entityWrapper.like("name",course.getName());
        }
        if(!StringUtils.isEmpty(course.getType())&&!inputParam.isOwn()){
            entityWrapper.eq("type",course.getType());
        }
        entityWrapper.eq("status",1);
        if(course.getDifficulty()!=null){
            entityWrapper.eq("difficulty",course.getDifficulty());
        }
        //账号角色
        if(currentUser.getRoleType().equals(Role.AREA)){
            if(inputParam.isOwn()){
                //校本课程，只查自己区域的
                entityWrapper.andNew(" juris_id ='"+currentUser.getJurisId()+"'");
            }else{
                //若是区管，查该区的所有课程
                entityWrapper.andNew("juris_id is null or juris_id ='"+currentUser.getJurisId()+"'");
            }
        }else if(currentUser.getRoleType().equals(Role.SCHOOL)){
            if(inputParam.isOwn()){
                //若是校管且校本课程，仅学校的课程
                entityWrapper.andNew("school_id ='"+currentUser.getSchoolId()+"'");
            }else{
                //若是校管，查学校的课程
                entityWrapper.andNew("juris_id is null or school_id ='"+currentUser.getSchoolId()+"'");
            }
        }else if(currentUser.getRoleType().equals(Role.SUPER)&&inputParam.isOwn()){
                //若是超管且校本课程
            entityWrapper.andNew("juris_id is not null ");

        }else if(currentUser.getRoleType().equals(Role.TEACHER)&&inputParam.isOwn()){
            //若是超管且校本课程
            entityWrapper.andNew("school_id ='"+currentUser.getSchoolId()+"'");

        }
        entityWrapper.orderBy("create_time",false);

        //查分页
        if(inputParam!=null && inputParam.getPage()!=null && inputParam.getSize()!=null
                && inputParam.getPage()>0 &&  inputParam.getSize()>0){
            Page<Course> page = new Page<Course>(inputParam.getPage(), inputParam.getSize());
            List<Course> tempList = this.baseMapper.selectPage(page,entityWrapper);
            Integer total = this.baseMapper.selectCount(entityWrapper);
            Map<String, Object> resultMap = new HashMap<String, Object>();
            for (Course course1 : tempList) {
                course1.setStatsInfo(computeById(course1.getId()));
            }
            resultMap.put("rows", tempList);
            resultMap.put("total", total);
            return ResponseInfo.success(resultMap);
        }else {//查全部
            List<Course> tempList = this.baseMapper.selectList(entityWrapper);
            for (Course course1 : tempList) {
                course1.setStatsInfo(computeById(course1.getId()));
            }
            return ResponseInfo.success(tempList);
        }
    }

    /**
     * @Author: HuangHaiShui
     * @Description: 根据教师的id查询教师的任课班级的课程
     * @Date: 14:32 2021/7/20
     * @param course:
     * @param inputParam:
     * @return: Map
     **/
    private Map getByTeacherId(Course course, InputParam inputParam){

        if(inputParam!=null && inputParam.getPage()!=null && inputParam.getSize()!=null
                && inputParam.getPage()>0 &&  inputParam.getSize()>0){
            Page<Course> page = new Page<Course>(inputParam.getPage(), inputParam.getSize());
            List<Course> tempList = this.baseMapper.findByTeachId(page,inputParam);
            Map<String, Object> resultMap = new HashMap<String, Object>();

            for (Course course1 : tempList) {
                course1.setStatsInfo(computeById(course1.getId()));
            }
            resultMap.put("rows", tempList);
            resultMap.put("total", page.getTotal());
            return ResponseInfo.success(resultMap);
        }else {//查全部
            inputParam.setPage(1);
            inputParam.setSize(50);
            Page<Course> page = new Page<Course>(inputParam.getPage(), inputParam.getSize());
            List<Course> tempList = this.baseMapper.findByTeachId(page,inputParam);
            for (Course course1 : tempList) {
                course1.setStatsInfo(computeById(course1.getId()));
            }
            return ResponseInfo.success(tempList);
        }
    }

    @Override
    public Map dele(Course course) {
        if(!StringUtils.isEmpty(course.getId())){
            //设置为不可用
            course.setStatus(0);
            this.baseMapper.updateById(course);
            //删除course_chapter_class里的所有关联数据

            courseChapterClassService.delete(
                    new EntityWrapper<CourseChapterClass>()
                            .eq("course_id",course.getId()));
        }
        return ResponseInfo.success(null);
    }

    @Override
    public Map getById(Course course, InputParam inputParam) {
        if(StringUtils.isEmpty(course.getId())) {
            return ResponseInfo.error(SystemParam.ERROR_PARAMS);
        }else{
            Course temp = this.selectById(course.getId());
            //查询课程的下属课时数据
            EntityWrapper entityWrapper =  new EntityWrapper<CourseChapter>();
            entityWrapper.eq("course_id",course.getId());
            entityWrapper.eq("status",1);
            entityWrapper.orderBy(
                    "num",true);
            List list = courseChapterService.selectList(entityWrapper);
            if(list.size()>0){
                temp.setChapterList(list);
            }
            temp.setStatsInfo(computeById(course.getId()));
            return ResponseInfo.success(temp);
        }

    }

    @Override
    public Map getAllAndRecord(InputParam inputParam) {
        //当前用户的信息
        User temp = userService.selectById(inputParam.getUserId());
        //教师播放视频
        if(temp.getRoleType().equals(Role.TEACHER)){
            return findAllByClsId(inputParam);
        }else if(temp.getRoleType().equals(Role.STUDENT)){
            return findAllByStuId(inputParam);
        }
        return ResponseInfo.success(null);
    }

    //根据学生的id以及课程id，获取这个学生的所有课时数据
    @Override
    public Map findAllByStuId(InputParam inputParam) {
        if(StringUtils.isEmpty(inputParam.getUserId())
            ||StringUtils.isEmpty(inputParam.getCourseId())) {
            return ResponseInfo.error(SystemParam.ERROR_PARAMS);
        }else {
            Course temp = this.baseMapper.findAllByStuId(inputParam);
            StatsInfo statsInfo = computeById(inputParam.getCourseId());
            //统计学生该课程的签到课时数据
            int selectCount = courseChapterSignService.selectCount(
                    new EntityWrapper<CourseChapterSign>()
                            .eq("course_id", inputParam.getCourseId())
                            .eq("user_id", inputParam.getUserId()));
            statsInfo.setSignChapter(selectCount);
            temp.setStatsInfo(statsInfo);
            return ResponseInfo.success(temp);
        }
    }


    private Map findAllByClsId(InputParam inputParam) {
        if(StringUtils.isEmpty(inputParam.getClassId())
                ||StringUtils.isEmpty(inputParam.getCourseId())) {
            return ResponseInfo.error(SystemParam.ERROR_PARAMS);
        }else {
            Course temp = this.baseMapper.findAllByClsId(inputParam);
            return ResponseInfo.success(temp);
        }
    }


    @Value("${upload.folderName}")
    private String folderName;
    @Override
    public Map photo(MultipartFile file, InputParam inputParam) throws IOException {
        if(StringUtils.isEmpty(inputParam.getCourseId())) {
            return ResponseInfo.error(SystemParam.ERROR_PARAMS);
        }else {
            String filename = FileUpload.writeUploadFile(file, folderName, "course");
            //TODO:每次上传前，先删除旧图片
            Course course = new Course();
            course.setId(inputParam.getCourseId());
            course.setCoverUrl(filename);
            this.baseMapper.updateById(course);
            return ResponseInfo.success(filename);
        }
    }

    /**
     * @Author: HuangHaiShui 
     * @Description: 统计该课程的数据 ，课时总数，课件总数，视频总数
     * @Date: 16:54 2021/8/19
     * @param id: 
     * @return: StatsInfo
     **/
    @Override
    public StatsInfo computeById(String id) {
        if(!StringUtils.isEmpty(id)) {
            StatsInfo statsInfo = new StatsInfo();
            //课时数量
            int countChapters = courseChapterService.selectCount(new EntityWrapper<CourseChapter>()
                    .eq("course_id", id)
                    .eq("status", 1));
            statsInfo.setChapters(countChapters);
            //文件数量
            int countDocs = courseChapterDocService.selectCount(new EntityWrapper<CourseChapterDoc>()
                    .eq("course_id", id)
                    .eq("status", 1));
            statsInfo.setDocs(countDocs);
            //视频数量
            int countVideos = courseChapterVideoService.selectCount(new EntityWrapper<CourseChapterVideo>()
                    .eq("course_id", id)
                    .eq("status", 1));
            statsInfo.setVideos(countVideos);
            return statsInfo;
        }
        return null;
    }

    @Override
    public List<Course> getByClsId(String clsId) {
        if(!StringUtils.isEmpty(clsId)) {
          return  this.baseMapper.getByClsId(clsId);
        }
        return null;
    }
}
